<template>
  <div class="home-container">
    <!-- 头部导航栏 -->
    <nav-header
      :navItems="navItems"
      :currentIndex="currentIndex"
      :isSliding="isSliding"
      :slideOffset="slideOffset"
      @tab-change="switchTab"
    />

    <!-- 内容区域 - 支持滑动 -->
    <main-content 
      :currentIndex="currentIndex" 
      @update:currentIndex="currentIndex = $event"
      @sliding-state-change="handleSlidingStateChange"
      @refresh="handleRefresh"
    >
      <!-- 关注页面 -->
      <template #tab-0>
        <follow-content />
      </template>
      
      <!-- 发现页面 -->
      <template #tab-1>
        <discover-content 
          :categoryData="currentTabData"
        />
      </template>
      
      <!-- 泸州页面 -->
      <template #tab-2>
        <div class="discover-content-container">
          <div 
            class="category-content-container"
          >
            <div 
              class="category-content-wrapper"
            >
              <div class="category-page" v-for="(category, catIndex) in currentTabData" :key="'cat-'+catIndex">
                <div class="discover-items">
                  <div class="discover-item" v-for="(item, index) in category.items" :key="'item-'+catIndex+'-'+index">
                    <div class="discover-image">
                      <div 
                        v-if="category.tagName" 
                        class="category-tag"
                        :class="getCategoryTagClass && getCategoryTagClass(category.type)"
                      >
                        {{ category.tagName }}
                      </div>
                      <img v-if="!item.isVideo" :src="item.cover" :alt="category.title + '图片'">
                      <VideoPoster
                        v-else
                        :videoSrc="item.cover"
                        width="100%"
                        height="100%"
                        :canvasWidth="320"
                        :canvasHeight="180"
                        @click="goToNoteDetail(item)"
                      />
                    </div>
                    <div class="discover-title">{{item.title}}</div>
                    <div class="discover-user">
                      <div class="user-info">
                        <img :src="item.avatar" class="small-avatar" alt="用户头像">
                        <span>{{item.username}}</span>
                      </div>
                      <div class="publish-date">
                        <svg class="calendar-icon" viewBox="0 0 24 24" fill="currentColor">
                          <path d="M19,4H18V2H16V4H8V2H6V4H5C3.9,4 3,4.9 3,6V20C3,21.1 3.9,22 5,22H19C20.1,22 21,21.1 21,20V6C21,4.9 20.1,4 19,4M19,20H5V10H19V20M19,8H5V6H19V8Z"/>
                        </svg>
                        <span class="date">{{ formatDate(item.time) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </main-content>
    
    <!-- 底部导航栏 -->
    <nav-footer />
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import NavHeader from '@/components/home/header/NavHeader.vue';
import MainContent from '@/components/home/content/MainContent.vue';
import FollowContent from '@/components/home/follow/FollowContent.vue';
import DiscoverContent from '@/components/home/discover/DiscoverContent.vue';
import CityContent from '@/components/home/city/CityContent.vue';
import NavFooter from '@/components/NavFooter.vue';
import VideoPoster from '@/components/VideoPoster.vue';
import axios from 'axios';

export default {
  name: 'Home',
  components: {
    NavHeader,
    MainContent,
    FollowContent,
    DiscoverContent,
    CityContent,
    NavFooter,
    VideoPoster
  },
  setup() {
    // 当前激活的标签索引
    const currentIndex = ref(1); // 默认选中"发现"页面
    
    // 滑动状态
    const isSliding = ref(false);
    const slideOffset = ref(0);
    
    // 处理滑动状态变化
    const handleSlidingStateChange = (state) => {
      isSliding.value = state.isSliding;
      slideOffset.value = state.slideOffset;
    };
    
    // 切换标签
    const switchTab = (index) => {
      currentIndex.value = index;
    };
    
    // 处理下拉刷新
    const handleRefresh = async () => {
      console.log('下拉刷新触发，当前页面索引:', currentIndex.value);
      
      // 根据当前页面索引执行不同的刷新逻辑
      try {
        if (currentIndex.value === 0) {
          // 刷新关注页
          window.dispatchEvent(new CustomEvent('followStatusChanged'));
        } else if (currentIndex.value === 1) {
          // 刷新发现页
          await fetchDiscoverData();
        } else if (currentIndex.value === 2) {
          // 刷新泸州页
          await fetchLuzhouData();
        }
        
        // 刷新完成后，直接重新加载页面
        setTimeout(() => {
          window.location.reload();
        }, 800);
      } catch (error) {
        console.error('刷新数据失败:', error);
      }
    };
    
    // 导航项
    const navItems = ref([
      { name: '关注' },
      { name: '发现' },
      { name: '泸州' }
    ]);
    
    // 发现页数据结构（动态获取所有笔记）
    const discoverCategoryData = ref([]);
    // 泸州城市数据（动态获取包含"泸州"关键词的笔记）
    const luzhouItems = ref([]);

    // 格式化日期为YYYY-MM-DD格式
    const formatDate = (timestamp) => {
      if (!timestamp) return '未知日期';
      
      try {
        const date = new Date(timestamp);
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return '未知日期';
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '未知日期';
      }
    };

    // 获取发现页数据
    const fetchDiscoverData = async () => {
      // 1. 获取所有用户，建立映射
      const userMap = new Map();
      const usersRes = await axios.get('http://1.14.98.17:8765/api/users');
      if (usersRes.data.success) {
        usersRes.data.data.forEach(user => {
          userMap.set(user.user_id, user);
        });
      }

      // 2. 获取所有笔记（发现页）
      const notesRes = await axios.get('http://1.14.98.17:8765/api/notes');
      if (notesRes.data.success) {
        const categoryMap = [
          { title: '短剧', type: 'drama', keywords: ['短剧', '剧情', '剧场'] },
          { title: '美食', type: 'food', keywords: ['美食', '吃', '餐', '菜', '食谱', '美味'] },
          { title: '穿搭', type: 'fashion', keywords: ['穿搭', '服饰', '搭配', '时尚'] },
          { title: '旅行', type: 'travel', keywords: ['旅行', '旅游', '景点', '游记'] },
          { title: '直播', type: 'live', keywords: ['直播'] },
        ];

        // 初始化分类
        const categories = categoryMap.map(cat => ({
          ...cat,
          items: [],
          tagName: cat.title
        }));
        const otherCategory = {
          title: '其他',
          type: 'other',
          tagName: '推荐',
          items: []
        };

        // 处理每个笔记
        const processedNotes = await Promise.all(notesRes.data.data.map(async note => {
          try {
            const user = userMap.get(note.user_id) || {};
            
            // 获取媒体信息
            let coverUrl = '';
            let isVideo = false;
            
            try {
              const mediaRes = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/media`);
              if (mediaRes.data.success && mediaRes.data.data && mediaRes.data.data.length > 0) {
                coverUrl = mediaRes.data.data[0].media_url;
                isVideo = mediaRes.data.data[0].media_type === 'video';
              }
            } catch (mediaError) {
              console.error('获取笔记媒体失败:', mediaError);
            }
            
            return {
              title: note.title || '无标题笔记',
              cover: coverUrl,
              avatar: user.avatar_url || '',
              username: user.nickname || '匿名用户',
              likes: note.like_count || 0,
              id: note.note_id,
              time: note.updated_at || note.create_time || '',
              isVideo: isVideo
            };
          } catch (error) {
            console.error('处理笔记数据失败:', error);
            return null;
          }
        }));

        // 过滤掉处理失败的笔记
        const validNotes = processedNotes.filter(note => note !== null);

        // 按照关键词分类笔记
        validNotes.forEach(note => {
          // 检查标题中是否包含任何类别的关键词
          const matchedCategory = categories.find(category =>
            category.keywords.some(keyword =>
              note.title.toLowerCase().includes(keyword.toLowerCase())
            )
          );

          if (matchedCategory) {
            matchedCategory.items.push(note);
          } else {
            otherCategory.items.push(note);
          }
        });

        // 只保留有笔记的分类
        const nonEmptyCategories = categories.filter(cat => cat.items.length > 0);
        nonEmptyCategories.push(otherCategory); // 添加其他分类
        
        // 更新数据
        discoverCategoryData.value = nonEmptyCategories;
      }
    };
    
    // 获取泸州页数据
    const fetchLuzhouData = async () => {
      // 1. 获取所有用户，建立映射
      const userMap = new Map();
      const usersRes = await axios.get('http://1.14.98.17:8765/api/users');
      if (usersRes.data.success) {
        usersRes.data.data.forEach(user => {
          userMap.set(user.user_id, user);
        });
      }
      
      // 2. 获取所有笔记并过滤包含"泸州"关键词的
      const notesRes = await axios.get('http://1.14.98.17:8765/api/notes');
      if (notesRes.data.success) {
        const filteredNotes = notesRes.data.data.filter(note => 
          (note.title && note.title.includes('泸州')) || 
          (note.description && note.description.includes('泸州'))
        );
        
        // 处理每个笔记
        const processedLuzhouNotes = await Promise.all(filteredNotes.map(async note => {
          try {
            const user = userMap.get(note.user_id) || {};
            
            // 获取媒体信息
            let coverUrl = '';
            let isVideo = false;
            
            try {
              const mediaRes = await axios.get(`http://1.14.98.17:8765/api/notes/${note.note_id}/media`);
              if (mediaRes.data.success && mediaRes.data.data && mediaRes.data.data.length > 0) {
                coverUrl = mediaRes.data.data[0].media_url;
                isVideo = mediaRes.data.data[0].media_type === 'video';
              }
            } catch (mediaError) {
              console.error('获取笔记媒体失败:', mediaError);
            }
            
            return {
              title: note.title || '无标题笔记',
              cover: coverUrl,
              avatar: user.avatar_url || '',
              username: user.nickname || '匿名用户',
              likes: note.like_count || 0,
              time: note.updated_at || note.create_time || '',
              isVideo: isVideo
            };
          } catch (error) {
            console.error('处理笔记数据失败:', error);
            return null;
          }
        }));
        
        // 过滤掉处理失败的笔记
        const validLuzhouNotes = processedLuzhouNotes.filter(note => note !== null);
        
        // 创建泸州分类
        const luzhouCategory = {
          title: '泸州',
          type: 'luzhou',
          tagName: '泸州',
          items: validLuzhouNotes
        };
        
        // 更新数据
        luzhouItems.value = [luzhouCategory];
      }
    };

    // 动态获取数据
    onMounted(async () => {
      await fetchDiscoverData();
      await fetchLuzhouData();
    });
    
    // 统一tab数据结构
    const currentTabData = computed(() => {
      if (currentIndex.value === 0) {
        // 关注
        return [{ title: '关注', type: 'follow', items: [] }];
      } else if (currentIndex.value === 1) {
        // 发现
        return discoverCategoryData.value;
      } else if (currentIndex.value === 2) {
        // 泸州
        return [{ title: '泸州', type: 'luzhou', items: luzhouItems.value }];
      }
      return [];
    });

    return {
      navItems,
      currentIndex,
      isSliding,
      slideOffset,
      handleSlidingStateChange,
      switchTab,
      discoverCategoryData,
      luzhouItems,
      currentTabData,
      formatDate,
      handleRefresh,
      fetchDiscoverData,
      fetchLuzhouData
    };
  }
}
</script>

<style scoped lang="less">
.home-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  
  /* 确保内容区域不被底部导航覆盖 */
  padding-bottom: 100px;
}
.discover-content-container {
  .category-content-container {
    overflow: hidden;
    .category-content-wrapper {
      display: flex;
      .category-page {
        flex: 0 0 100%;
        width: 100%;
        padding: 10px;
        .discover-items {
          display: flex;
          flex-wrap: wrap;
          width: 100%;
          max-width: 760px;
          margin: 0 auto;
          justify-content: space-between;
          .discover-item {
            width: calc(50% - 10px);
            height: 660px;
            margin: 10px 0;
            background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            .discover-image {
              position: relative;
              height: 476px;
              overflow: hidden;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
              .category-tag {
                position: absolute;
                top: 12px;
                left: 12px;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 14px;
                color: #fff;
                z-index: 2;
              }
              .live-tag {
                background-color: #ff2442;
              }
              .drama-tag {
                background-color: #ff8f00;
              }
            }
            .discover-title {
              width: 100%;
              height: 72px;
              margin: 15px 0 25px 3px;
              font-size: 28px;
              line-height: 1.3;
              font-weight: bold;
              color: #000;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              line-clamp: 2;
              -webkit-box-orient: vertical;
            }
            .discover-user {
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin: 0 15px;
              .user-info {
                display: flex;
                align-items: center;
                .small-avatar {
                  width: 34px;
                  height: 34px;
                  border-radius: 50%;
                  margin-right: 8px;
                }
                span {
                  font-size: 24px;
                  color: #666;
                  max-width: 130px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }
              }
              .publish-date {
                display: flex;
                align-items: center;
                padding: 5px 10px;
                background-color: rgba(0, 0, 0, 0.03);
                border-radius: 16px;
                
                .calendar-icon {
                  width: 20px;
                  height: 20px;
                  margin-right: 6px;
                  color: #666;
                }
                
                .date {
                  font-size: 20px;
                  color: #666;
                  font-weight: 500;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style> 